﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Estimate.Common.DBFieldTypes;
using Estimate.Common.Repository;
using Estimate.Common.Entity;
using Estimate.Common.Estimate;
using Newtonsoft.Json;

namespace Estimate.Reports
{
    /// <summary>
    /// 集体得分排名报表类
    /// </summary>
    public class CollectionRankReport
    {
        #region 变量与对象
        /// <summary>
        /// 计算数据了类型
        /// </summary>
        enum CulculateType
        {
            HomeData,//计算首页报表数据
            CollectionData//计算集体表数据
        }

        #region 用于排序的值
        /// <summary>
        /// 用于按照特定的值排序
        /// </summary>
        static Dictionary<IComparer<KeyValuePair<string, Dictionary<string, object>>>, object[]> config = new Dictionary<IComparer<KeyValuePair<string, Dictionary<string, object>>>, object[]>()
            {
                { new IndividualCityScoreComparer_WaterSkill(),new object[]{"晴雨24小时技巧值","FD24_Water_Skill"}},
                { new IndividualCityScoreComparer_MaxTSkill(), new object[]{"最高温24小时技巧值","FD24_MaxT_Skill"}},
                { new IndividualCityScoreComparer_MinTSkill(),new object[]{"最低温24小时技巧值","FD24_MinT_Skill"} },

                { new IndividualCityScoreComparer_MaxTemp(ForeSpanType.FD00_24),new object[]{"24小时最高温","max",ForeSpanType.FD00_24} },
                { new IndividualCityScoreComparer_MinTemp(ForeSpanType.FD00_24),new object[]{"24小时最低温","min",ForeSpanType.FD00_24} },
                { new IndividualCityScoreComparer_WaterfallAmount(ForeSpanType.FD00_24),new object[]{"24小时晴雨","wth",ForeSpanType.FD00_24} },

                { new IndividualCityScoreComparer_MaxTemp(ForeSpanType.FD24_48),new object[]{"48小时最高温","max",ForeSpanType.FD24_48} },
                { new IndividualCityScoreComparer_MinTemp(ForeSpanType.FD24_48),new object[]{"48小时最低温","min",ForeSpanType.FD24_48} },
                { new IndividualCityScoreComparer_WaterfallAmount(ForeSpanType.FD24_48),new object[]{"48小时晴雨","wth",ForeSpanType.FD24_48} },

                { new IndividualCityScoreComparer_MaxTemp(ForeSpanType.FD48_72),new object[]{"72小时最高温","max",ForeSpanType.FD48_72} },
                { new IndividualCityScoreComparer_MinTemp(ForeSpanType.FD48_72),new object[]{"72小时最低温","min",ForeSpanType.FD48_72} },
                { new IndividualCityScoreComparer_WaterfallAmount(ForeSpanType.FD48_72),new object[]{"72小时晴雨","wth",ForeSpanType.FD48_72} },

                { new IndividualCityScoreComparer_MaxTemp(ForeSpanType.FD72_96),new object[]{"96小时最高温","max",ForeSpanType.FD72_96} },
                { new IndividualCityScoreComparer_MinTemp(ForeSpanType.FD72_96),new object[]{"96小时最低温","min",ForeSpanType.FD72_96} },
                { new IndividualCityScoreComparer_WaterfallAmount(ForeSpanType.FD72_96),new object[]{"96小时晴雨","wth",ForeSpanType.FD72_96} },

                { new IndividualCityScoreComparer_MaxTemp(ForeSpanType.FD96_120),new object[]{"120小时最高温","max",ForeSpanType.FD96_120} },
                { new IndividualCityScoreComparer_MinTemp(ForeSpanType.FD96_120),new object[]{"120小时最低温","min",ForeSpanType.FD96_120} },
                { new IndividualCityScoreComparer_WaterfallAmount(ForeSpanType.FD96_120),new object[]{"120小时晴雨","wth",ForeSpanType.FD96_120} }
            };
        #endregion

        CollectionRankType _type;
        private Dictionary<string, string> cityCodes;
        public Dictionary<string, string> CityCodes
        {
            get
            {
                return cityCodes;
            }
        }

        private FullInfoReport memberReportScore;// 得分对象
        public FullInfoReport MemberReportScore
        {
            get
            {
                return memberReportScore;
            }
        }
        private FullInfoReport standardReportScore;// 标准评分对象
        public FullInfoReport StandardReportScore
        {
            get
            {
                return standardReportScore;
            }
        }
        ExecutionStatus exeStatus;//程序执行状态
        CollectionRankResult Result = new CollectionRankResult();
        protected string _connectionString;
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数，用于首页数据生成
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="type"></param>
        public CollectionRankReport(string connectionString, CollectionRankType type)    
        {
            _connectionString = connectionString;
            _type = type;
            this.Initial(CulculateType.HomeData);
        }

        public CollectionRankReport(string connectionString, CollectionRankType type,string tid)
        {
            _connectionString = connectionString;
            _type = type;

            if (tid != "") exeStatus = new ExecutionStatus(tid);
            if (exeStatus != null) exeStatus.SetMessage("Initial", "程序正在准备...");

            this.Initial(CulculateType.CollectionData);

            if (exeStatus != null) exeStatus.DeleteMessage("Initial");
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="ForeRepository">获取数据的对象</param>
        /// <param name="cityCodes">需要计算成绩的城市</param>
        public CollectionRankReport(string connectionString, ForeRepository foreRepository, Dictionary<string, string> CityCodes)
        {
            _connectionString = connectionString;
            cityCodes = CityCodes;
            memberReportScore = new FullInfoReport(connectionString, foreRepository, cityCodes);
            memberReportScore.CulculateWeatherScore = true;
            memberReportScore.CulculateWaterfallAmountWaterScore=true;
            memberReportScore.CulculateMaxTempScore = true;
            memberReportScore.CulculateMinTempScore = true;

            standardReportScore = new FullInfoReport(connectionString, ForeRepositoryFactory.ZytCityForeRepository(connectionString), CityCodes);
            standardReportScore.CulculateWeatherScore = true;
            standardReportScore.CulculateWaterfallAmountWaterScore = true;
            standardReportScore.CulculateMaxTempScore = true;
            standardReportScore.CulculateMinTempScore = true;
            
        }
        #endregion

        #region 初始化
        public void Clear()
        {
            memberReportScore.Clear();
            standardReportScore.Clear();
            Result.success = true.ToString();
            Result.msg = "";
            Result.result = new Dictionary<string, List<City>>();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private  void Initial(CulculateType type)
        {           
            //根据指定的站点类型,初始化 _destStations
            StationMatchRepository stationMatchRepository = new StationMatchRepository(_connectionString);

            StationMatchStationsType stationType = StationMatchStationsType.area;
            
            if (_type == CollectionRankType.area)
            {
                stationType = StationMatchStationsType.area;
                cityCodes = stationMatchRepository.GetAllNameStationDictionary(stationType, StationMatchExtralType.cz);
            }
            else if (_type == CollectionRankType.city)
            {
                stationType = StationMatchStationsType.city;
                cityCodes = stationMatchRepository.GetAllNameStationDictionary(stationType, StationMatchExtralType.cz);
            }
            else
            {

                stationType = StationMatchStationsType.station;
                AffiliationRepository affiliationRepository = new AffiliationRepository(_connectionString);
                cityCodes = affiliationRepository.GetAllStations();
                //由于 58248 镇江站已经取消，使用的是58252. 但是预报数据中一直使用的是58248
                //所以，将 镇江 站的站 手动修正为 58248
                cityCodes["镇江"] = "58248";
                //省台没有城镇报
                cityCodes.Remove("省台");
            }

            memberReportScore = new FullInfoReport(_connectionString, ForeRepositoryFactory.NormalCityForeRepository(_connectionString), cityCodes);

            standardReportScore = new FullInfoReport(_connectionString, ForeRepositoryFactory.ZytCityForeRepository(_connectionString), cityCodes);
            
            if (type == CulculateType.HomeData)
            {
                memberReportScore.CulculateWeatherScore = true;
                memberReportScore.CulculateWaterfallAmountWaterScore = true;
                memberReportScore.CulculateMaxTempScore = true;
                memberReportScore.CulculateMinTempScore = true;

                standardReportScore.CulculateWeatherScore = true;
                standardReportScore.CulculateWaterfallAmountWaterScore = true;
                standardReportScore.CulculateMaxTempScore = true;
                standardReportScore.CulculateMinTempScore = true;

            }
            else if (type == CulculateType.CollectionData)
            {
                memberReportScore.CulculateAllResult = true;
                memberReportScore.CulculateDeviationResult = false;

                standardReportScore.CulculateAllResult = true;
                standardReportScore.CulculateDeviationResult = false;
            }
           
        }
        #endregion

        #region 数据准备并计算
        public  void PrepareData(DateTime beginDate, DateTime endDate,ForeSemiType semitype, ForeSpanType[] spans, ForeSendpointType[] sendpoints)
        {
            try
            {
                if (exeStatus != null)
                {
                    exeStatus.TotalSteps = memberReportScore.GetExeStatusTotalSteps(beginDate, endDate, semitype, spans, spans) + standardReportScore.GetExeStatusTotalSteps(beginDate, endDate, semitype, spans, spans);
                    exeStatus.SetMessage("memberReportScore", "得分计算程序正在计算标准得分");
                }

                memberReportScore.PrepareData(beginDate, endDate, semitype, spans, spans, sendpoints);

                if (exeStatus != null)
                {
                    exeStatus.DeleteMessage("memberReportScore");
                    exeStatus.SetMessage("standardReportScore", "得分计算程序正在计算技巧值评分标准");
                }

                //ForeSpanType[] spans1;
                //if (type == CulculateType.HomeData)
                //    spans1 = new ForeSpanType[] { ForeSpanType.FD00_24 };//spans只用FD00_24,是因为首页数据技巧值只计算00_24
                //else if (type == CulculateType.CollectionData)
                //    spans1 = spans;

                standardReportScore.PrepareData(beginDate, endDate, semitype, spans, spans, sendpoints);

                if (exeStatus != null) exeStatus.DeleteMessage("standardReportScore");
            }
            catch(Exception ex)
            {
                Result.success = false.ToString();
                Result.msg = ex.Message;
            }
        }
        #endregion

        #region 获取首页报表数据中城市排名
        /// <summary>
        /// 获取首页数据中城市排名字符串
        /// </summary>
        /// <param name="previousScoreResult">(上个月或上上个月...的得分)与本次得分对比，得出名次和得分的趋势</param>
        /// <returns></returns>
        public string GetScoreResult(string previousScoreResult)
        {
            List<ResultScore> previousScore = null;
            if (previousScoreResult != null && previousScoreResult != string.Empty)
                previousScore = JsonConvert.DeserializeObject<List<ResultScore>>(previousScoreResult);

            return JsonConvert.SerializeObject(GetScoreResult(previousScore));
        }

        public List<ResultScore> GetScoreResult(List<ResultScore> previousScore)
        {
            Dictionary<string, Dictionary<string, object>> scores = GetRankResult(standardReportScore);

            List<KeyValuePair<string, Dictionary<string, object>>> scoreList = new List<KeyValuePair<string, Dictionary<string, object>>>();

            foreach (KeyValuePair<string, Dictionary<string, object>> pair in scores)
                scoreList.Add(pair);

            List<ResultScore> resultScores = new List<ResultScore>();
           
            int count = 0;

            foreach (KeyValuePair<IComparer<KeyValuePair<string, Dictionary<string, object>>>, object[]> pair in config)
            {
                scoreList.Sort(pair.Key);//排序
                count++;

                ResultScore resultScore = new ResultScore();
                List<CityScore> cities = new List<CityScore>();
                ResultScore previousResultScore = GetPreviousResultScore(previousScore, pair.Value[0].ToString());//取出当前类型用于对比的数据：晴雨24小时技巧值、最高温24小时技巧值、最低温24小时技巧值、24小时最高温 ......

                float totalScore = 0;//当前类型数据的总分

                for (int i = 0; i < scoreList.Count; i++)
                {
                    CityScore city = new CityScore();
                    city.name = scoreList[i].Key;
                    city.order = i + 1;

                    if (pair.Value.Length == 2)
                        city.score = scoreList[i].Value[pair.Value[1].ToString()].ToString();
                    else if (pair.Value.Length == 3)
                    {
                        if (scoreList[i].Value[pair.Value[1].ToString()] is Dictionary<ForeSpanType, TempScore>)
                        {
                            Dictionary<ForeSpanType, TempScore> ob = (Dictionary<ForeSpanType, TempScore>)scoreList[i].Value[pair.Value[1].ToString()];
                            TempScore score = (TempScore)ob[(ForeSpanType)pair.Value[2]];
                            city.score = score.Tt2.ToString();
                        }
                        else if (scoreList[i].Value[pair.Value[1].ToString()] is Dictionary<ForeSpanType, WaterScore>)
                        {
                            Dictionary<ForeSpanType, WaterScore> ob = (Dictionary<ForeSpanType, WaterScore>)scoreList[i].Value[pair.Value[1].ToString()];
                            WaterScore score = (WaterScore)ob[(ForeSpanType)pair.Value[2]];
                            city.score = score.PC.ToString();
                        }
                    }

                    CityScore previousCity = GetPreviousCityScore(previousResultScore, scoreList[i].Key);//取出当前城市用于比较的数据

                    if (previousCity != null)
                    {//算趋势
                        if (city.order < previousCity.order)
                            city.order_trend = "U";
                        else if (city.order > previousCity.order)
                            city.order_trend = "D";
                        else
                            city.order_trend = "S";

                        if (double.Parse(String.Format("{0:N2}", float.Parse(city.score))) > double.Parse(previousCity.score))
                            city.score_trend = "U";
                        else if (double.Parse(String.Format("{0:N2}", float.Parse(city.score))) < double.Parse(previousCity.score))
                            city.score_trend = "D";
                        else
                            city.score_trend = "S";
                    }

                    totalScore += float.Parse(city.score);
                    city.score = String.Format("{0:N2}", float.Parse(city.score));
                    cities.Add(city);
                }
                cities.Add(new CityScore("平均", String.Format("{0:N2}", totalScore / scoreList.Count), 0, "", ""));
                resultScore.cities = cities;
                resultScore.position = count.ToString();
                resultScore.name = pair.Value[0].ToString();
                totalScore = 0;
                resultScores.Add(resultScore);
            }
            return resultScores;
        }

        private ResultScore GetPreviousResultScore(List<ResultScore> previousScore, string scoreName)
        {
            if (previousScore == null)
                return null;
            else
                foreach (ResultScore rs in previousScore)
                {
                    if (rs.name == scoreName)
                        return rs;
                }
            return null;
        }
        private CityScore GetPreviousCityScore(ResultScore previousResultScore, string cityName)
        {

            if (previousResultScore == null)
                return null;
            else
                foreach (CityScore cs in previousResultScore.cities)
                {
                    if (cs.name == cityName)
                        return cs;
                }
            return null;
        }

        /// <summary>
        /// 计算城市得分排名
        /// 返回结果为嵌套的Dictionary 
        /// key1:城市名;key2:积分类型，包括wth,temp,FD24_Water_Skill,FD24_MaxT_Skill,FD24_MinT_Skill,MixPC,MixMaxTt2,MixMinTt2
        /// </summary>
        /// <param name="standardReport">用来比较的标准数据</param>
        /// <returns></returns>
        public Dictionary<string, Dictionary<string, object>> GetRankResult(FullInfoReport standardReport)
        {
            Dictionary<string, Dictionary<string, object>> result = new Dictionary<string, Dictionary<string, object>>();

            foreach (KeyValuePair<string, string> city in cityCodes)
                FillRankResult(result, city.Key, city.Value, standardReport);

            return result;

        }

        /// <summary>
        /// 填充得分字典(首页数据报表)
        /// </summary>
        /// <param name="result">得分字典</param>
        /// <param name="resultKey"></param>
        /// <param name="valueKey"></param>
        /// <param name="standardReport"></param>
        private void FillRankResult(Dictionary<string, Dictionary<string, object>> result, string resultKey, string valueKey, FullInfoReport standardReport)
        {
            result.Add(resultKey, new Dictionary<string, object>());
            result[resultKey].Add("wth", memberReportScore.WaterfallAmountWaterScore[valueKey]);

            result[resultKey].Add("max", memberReportScore.MaxTempScore[valueKey]);
            result[resultKey].Add("min", memberReportScore.MinTempScore[valueKey]);

            //  FD00_24小时晴雨技巧值
            float Water_Skill = GlobalFunction.CalculateWaterSkill(memberReportScore.WaterfallAmountWaterScore[valueKey][ForeSpanType.FD00_24].PC, standardReportScore.WaterfallAmountWaterScore[valueKey][ForeSpanType.FD00_24].PC);
            result[resultKey].Add("FD24_Water_Skill", Water_Skill);

            //FD00_24最高温技巧值
            float MaxT_Skill = GlobalFunction.CalculateTempSkill(memberReportScore.MaxTempScore[valueKey][ForeSpanType.FD00_24].Tt2, standardReportScore.MaxTempScore[valueKey][ForeSpanType.FD00_24].Tt2);
            result[resultKey].Add("FD24_MaxT_Skill", MaxT_Skill);

            //FD00_24最低温技巧值
            float Min_Skill = GlobalFunction.CalculateTempSkill(memberReportScore.MinTempScore[valueKey][ForeSpanType.FD00_24].Tt2, standardReportScore.MinTempScore[valueKey][ForeSpanType.FD00_24].Tt2);
            result[resultKey].Add("FD24_MinT_Skill", Min_Skill);


            float MixPC = -1;
            if (MixPC == -1)
            {
                MixPC = 0;

                MixPC += memberReportScore.WaterfallAmountWaterScore[valueKey][ForeSpanType.FD00_24].PC * 10;
                MixPC += memberReportScore.WaterfallAmountWaterScore[valueKey][ForeSpanType.FD24_48].PC * 8;
                MixPC += memberReportScore.WaterfallAmountWaterScore[valueKey][ForeSpanType.FD48_72].PC * 6;
                MixPC += memberReportScore.WaterfallAmountWaterScore[valueKey][ForeSpanType.FD72_96].PC * 2;
                MixPC += memberReportScore.WaterfallAmountWaterScore[valueKey][ForeSpanType.FD96_120].PC * 1;

                MixPC /= 27;
            }
            result[resultKey].Add("MixPC", MixPC);


            float MixMaxTt2 = -1;
            if (MixMaxTt2 == -1)
            {
                MixMaxTt2 = 0;

                MixMaxTt2 += memberReportScore.MaxTempScore[valueKey][ForeSpanType.FD00_24].Tt2 * 10;
                MixMaxTt2 += memberReportScore.MaxTempScore[valueKey][ForeSpanType.FD24_48].Tt2 * 8;
                MixMaxTt2 += memberReportScore.MaxTempScore[valueKey][ForeSpanType.FD48_72].Tt2 * 6;
                MixMaxTt2 += memberReportScore.MaxTempScore[valueKey][ForeSpanType.FD72_96].Tt2 * 2;
                MixMaxTt2 += memberReportScore.MaxTempScore[valueKey][ForeSpanType.FD96_120].Tt2 * 1;

                MixMaxTt2 /= 27;
            }
            result[resultKey].Add("MixMaxTt2", MixMaxTt2);


            float MixMinTt2 = -1;
            if (MixMinTt2 == -1)
            {
                MixMinTt2 = 0;

                MixMinTt2 += memberReportScore.MinTempScore[valueKey][ForeSpanType.FD00_24].Tt2 * 10;
                MixMinTt2 += memberReportScore.MinTempScore[valueKey][ForeSpanType.FD24_48].Tt2 * 8;
                MixMinTt2 += memberReportScore.MinTempScore[valueKey][ForeSpanType.FD48_72].Tt2 * 6;
                MixMinTt2 += memberReportScore.MinTempScore[valueKey][ForeSpanType.FD72_96].Tt2 * 2;
                MixMinTt2 += memberReportScore.MinTempScore[valueKey][ForeSpanType.FD96_120].Tt2 * 1;

                MixMinTt2 /= 27;
            }
            result[resultKey].Add("MixMinTt2", MixMinTt2);

            result[resultKey].Add("SumOrder", 0.0);

            result[resultKey].Add("Order", 0);

            //_individualRecordCount加上standardReport的_individualRecordCount是否合理？？？？？
            //if (standardReport.RecordCount != null && standardReport.RecordCount.Count > 0)
            //{
            //    foreach (KeyValuePair<ForeSpanType, int> pair in standardReport.RecordCount[valueKey])
            //    {
            //        if (memberReportScore.RecordCount[valueKey].ContainsKey(pair.Key))
            //            memberReportScore.RecordCount[valueKey][pair.Key] += pair.Value;
            //        else
            //            memberReportScore.RecordCount[valueKey].Add(pair.Key, pair.Value);
            //    }
            //}

            int RecordCount = memberReportScore.GetTotalRecordCount(valueKey);

            //if (memberReportScore.RecordCount != null && memberReportScore.RecordCount.Count > 0)
            //{
            //    foreach (KeyValuePair<ForeSpanType, int> pair in memberReportScore.RecordCount[valueKey])
            //        RecordCount += pair.Value;
            //}
            result[resultKey].Add("RecordCount", RecordCount);
        }

        #endregion

        #region 获取集体排名表数据
        /// <summary>
        /// 获取城市集体得分表字符串
        /// </summary>
        /// <returns></returns>
        public string GetCityScoreResultString()
        {
           List<City> citylist=new List<City>();

           foreach (KeyValuePair<string, string> city in cityCodes)
               citylist.Add(new City(city.Key, memberReportScore.ToResult(standardReportScore, city.Value)));

           Result.result.Add("data", citylist);

           return JsonConvert.SerializeObject(Result);
        }

        #endregion

        #region 获取台站排名报表数据(缓存用)

        /// <summary>
        /// 获取台站排名字符串
        /// </summary>
        /// <returns></returns>
        public string GetStationRankReportDataString()
        {
            List<Dictionary<string, object>> StationScoreList = GetStationRankReportData();
            SortResult(StationScoreList);
            return JsonConvert.SerializeObject(StationScoreList);
        }

        private List<Dictionary<string, object>> GetStationRankReportData()
        {
            //List<Station> StationScoreList = new List<Station>();//排名结果
            List<Dictionary<string, object>> StationScoreList = new List<Dictionary<string, object>>();

            foreach (KeyValuePair<string, string> city in cityCodes)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();

                result.Add("name", city.Key);
                result.Add("position", 0);
                result.Add("RecordCount",  memberReportScore.GetTotalRecordCount(city.Value));
                result.Add("Composition", float.Parse(String.Format("{0:N2}", memberReportScore.CalCollectCompositeScore(city.Value))));
               
                foreach (KeyValuePair<ForeSpanType,Dictionary<DateTime, int>> pair in memberReportScore.RecordCount[city.Value])
                {
                    string[] strs = pair.Key.ToString().Split('_');
                    string key = strs[1];

                    if (pair.Key == ForeSpanType.FD00_24)
                    {
                        //晴雨技巧值
                        float Water_Skill = GlobalFunction.CalculateWaterSkill(memberReportScore.WaterfallAmountWaterScore[city.Value][pair.Key].PC, standardReportScore.WaterfallAmountWaterScore[city.Value][pair.Key].PC);
                        result.Add("pc_skill_" + key, float.Parse(String.Format("{0:N2}", Water_Skill)));

                        //最高温技巧值
                        float MaxT_Skill = GlobalFunction.CalculateTempSkill(memberReportScore.MaxTempScore[city.Value][pair.Key].Tt2, standardReportScore.MaxTempScore[city.Value][pair.Key].Tt2);
                        result.Add("maxt2_skill_" + key, float.Parse(String.Format("{0:N2}", MaxT_Skill)));

                        //最低温技巧值
                        float Min_Skill = GlobalFunction.CalculateTempSkill(memberReportScore.MinTempScore[city.Value][pair.Key].Tt2, standardReportScore.MinTempScore[city.Value][pair.Key].Tt2);
                        result.Add("mint2_skill_" + key, float.Parse(String.Format("{0:N2}", Min_Skill)));
                    }
                    result.Add("pc_" + key, float.Parse(String.Format("{0:N2}", memberReportScore.WaterfallAmountWaterScore[city.Value][pair.Key].PC)));
                    result.Add("maxt2_" + key, float.Parse(String.Format("{0:N2}", memberReportScore.MaxTempScore[city.Value][pair.Key].Tt2)));
                    result.Add("mint2_" + key, float.Parse(String.Format("{0:N2}", memberReportScore.MinTempScore[city.Value][pair.Key].Tt2)));
                    
                }
               
                //StationScoreList.Add(new Station(city.Key, 0,, score));
                StationScoreList.Add(result);
            }


            return StationScoreList;
        }

        private void SortResult(List<Dictionary<string, object>> StationScoreList)
        {
            StationScoreList.Sort(new StationCompositeScore("Composition"));
           
            for (int i = 0; i < StationScoreList.Count; i++)
                StationScoreList[i]["position"] = i + 1;

            //List<Station> frontList = new List<Station>();
            //List<Station> lastList = new List<Station>();
            //List<Station> zeroList = new List<Station>();


            //先按记录数排名
            //StationScoreList.Sort(new StationCompositeScore("RecordCount"));

            //double avgCount = 0;
            //double sumCount = 0;
            //double zeroCount = 0;
            //foreach (Station Score in StationScoreList)
            //{
            //    sumCount += (int)Score.score["RecordCount"];
            //    if ((int)Score.score["RecordCount"] == 0)
            //        zeroCount += 1;
            //}
            //avgCount = sumCount * 1.0 / (StationScoreList.Count - zeroCount);//平均样本数
            //double lineCount = avgCount * 0.6;//平均样本数的60%

            //foreach (Station Score in StationScoreList)
            //{
            //    if ((int)Score.score["RecordCount"] >= lineCount)
            //        frontList.Add(Score);//样本数大于等于平均样本数的60%,则靠前排
            //    else if ((int)Score.score["RecordCount"] > 0)
            //        lastList.Add(Score);
            //    else
            //        zeroList.Add(Score);
            //}

            //StationScoreList.Clear();

            //frontList.Sort(new StationCompositeScore("Composition"));
            //for (int i = 1; i <= frontList.Count; i++)
            //{
            //    frontList[i - 1].position = i;
            //    StationScoreList.Add(frontList[i - 1]);
            //}

            //lastList.Sort(new StationCompositeScore("Composition"));
            //for (int i = 1; i <= lastList.Count; i++)
            //{
            //    lastList[i - 1].position = i + frontList.Count;
            //    StationScoreList.Add(lastList[i - 1]);
            //}

            //for (int i = 0; i < zeroList.Count; i++)
            //    StationScoreList.Add(zeroList[i]);
        }

        #endregion
    }


    #region 用于JSON序列化首页数据中城市排名结果
    public class ResultScore
    {
        public string name;
        public string position;
        public List<CityScore> cities = new List<CityScore>();
    }

    public class CityScore
    {
        public string name;
        public string score;
        public int order;
        public string order_trend = "";
        public string score_trend = "";

        public CityScore()
        { }

        public CityScore(string Name, string Score, int Order, string Order_trend, string Score_trend)
        {
            name = Name;
            score = Score;
            order = Order;
            order_trend = Order_trend;
            score_trend = Score_trend;
        }

        public CityScore Copy()
        {
            CityScore s = new CityScore();
            s.name = this.name;
            s.score = this.score;
            return s;
        }
    }
    #endregion

    #region 用于JSON序列化集体排名表数据
    public class City
    {
        public string name;
        public object value;

        public City(string Name,object Value)
        {
            name = Name;
            value = Value;
        }
    }

    public class CollectionRankResult
    {
        public string success = true.ToString();
        public string msg = "";
        public Dictionary<string, List<City>> result = new Dictionary<string, List<City>>();

        public CollectionRankResult()
        {
            //result.Add("data", new List<City>());
        }
    }
#endregion

}
